import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import { useState, useEffect, useRef } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';

import NineImage from '../../components/NineImage';
import PageHeader from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext';
import ProcessTitle from '../../components/processStep/processTitle';
import ProcessStatus from '../../components/processStep/processStatus';
import { CompleteButton, NextButton } from '../../components/processStep/processButton';
import { getUserProgressStepApi, setUserProgressStepStatusApi } from '../../api/myself';

import '../user-study-time/index.scss';

const StudyTimeStandard = () => {
  const firstLoadRef = useRef<boolean>(false);
  const [userStep, setUserStep] = useState<any>({
    id: 0,
    name: "",
    status: 0,
    completed_time: "",
    children: []
  });
  const [showTextContent, setShowTextContent] = useState('image');
  const stepId = Taro.getCurrentInstance().router?.params?.stepId || '9';
  const { setCarSubjectStepProcessStatus } = useAppContext();

  // 获取初始化信息
  const getInitInfoData = async () => {
    try {
      const res = await getUserProgressStepApi(Number(stepId));
      if(res.code === 200 && res.data.length == 1) {
        const result = res.data[0];
        setUserStep({
          id: stepId,
          name: result.name,
          status: result.status,
          completed_time: result.created_at,
          children: result.children?.split(',') || [],
        });
      }
    } catch(err) {
      console.log(err);
      Taro.showToast({ title: '获取用户进度失败', icon: 'none' });
    }
  }

  // 更新步骤状态
  const updateStepStatus = async () => {
    try {
      const res = await setUserProgressStepStatusApi(Number(stepId), 1);
      if(res.code === 200) {
        setUserStep({
          ...userStep,
          status: 2
        });
        Taro.showToast({ title: '已完成学时查询~', icon: 'success' });
        setCarSubjectStepProcessStatus(Number(stepId), 1);
      }
    } catch(err) {
      console.log(err);
      Taro.showToast({ title: '预约失败，请稍后重试~', icon: 'none' });
    }
  }

  useEffect(() => {
    if (!stepId) return;
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      getInitInfoData();
    }
  }, []);

  return (
    <View className="page-container study-time-container">
      <PageHeader title="确认学时" />
      {userStep.completed_time && (
        <ProcessStatus title={userStep.name} createTime={userStep.completed_time} />
      )}

      <View className="study-time-content-container">
        <View className="main-card">
          <ProcessTitle 
            content="确认学时是否打满"
            showTextContent={showTextContent} 
            setShowTextContent={setShowTextContent} 
          />

          <View className="study-time-steps">
            {showTextContent == 'text' && (
              <ScrollView scrollY>
                <View className="steps-list">
                  <View className="step-item">
                    <View className="step-time-number">1</View>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>微信搜索：<Text className='importance-text'>上海计时驾培服务平台</Text></View>
                        <View>点击<Text className='importance-text'>学员入口</Text></View>
                        <View>通过短信找到学员编号</View>
                      </View>
                    </View>
                  </View>

                  <View className="step-item">
                    <Text className="step-time-number">2</Text>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>找到<Text className='importance-text'>学时明细确认</Text></View>
                        <View>点击<Text className='importance-text'>全部确认</Text></View>
                      </View>
                    </View>
                  </View>

                  <View className="step-item">
                    <Text className="step-time-number">3</Text>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>点击<Text className='importance-text'>学时汇总确认</Text></View>
                        <View>点击<Text className='importance-text'>汇总确认</Text></View>
                      </View>
                    </View>
                  </View>

                  <View className="step-item">
                    <Text className="step-time-number">4</Text>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>点击<Text className='importance-text'>各科目学时汇总</Text></View>
                        <View>点击<Text className='importance-text'>第二部分(科目二)</Text></View>
                      </View>
                    </View>
                  </View>
                </View>
              </ScrollView>
            )}
            {showTextContent == 'image' &&(
              <NineImage images={null} stepId={stepId}/>
            )}
          </View>

          {/* 特别注意 */}
          <View className="study-time-notice">
            <View className="notice-title">
              <MaterialIcons name="info" size={20} color="#e6a23c" className="mr-2" />
              <Text className="notice-title-text text-lg">特别注意</Text>
            </View>
            <View className="notice-content">
              {stepId === '9' ? (
                <View>
                  <View className='text-md'>C2：实车训练学时为<Text className='importance-text'>12学时</Text></View>
                  <View className='text-md'>C1：实车训练学时为<Text className='importance-text'>16学时</Text></View>
                </View>
              ) : (
                <View>
                  <View className='text-md'>科目三：实车训练学时为<Text className='importance-text'>24学时</Text></View>
                </View>
              )}
            </View>
          </View>

          {/* 底部按钮 */}
          <View className="button-container">
            {userStep.status === 0 ? (
              <CompleteButton onClick={updateStepStatus} content='确认学时已打满'/>
            ) : (
              <NextButton onClick={() => {
                Taro.navigateTo({
                  url: `/pages/user-subject-appointment/index?stepId=${Number(stepId) + 1}`
                });
              }} />
            )}
          </View>
        </View>
      </View>
    </View>
  );
};

export default StudyTimeStandard;
